//
//  SocketStringReader.m
//  Socket.IO-Client
//
//  Created by alanwang.dev on 16/8/8.
//  Copyright © 2016年 com.alanwang.dev. All rights reserved.
//

#import "SocketStringReader.h"

@implementation SocketStringReader

- (id) initWithMessage:(NSString *)message {
  if (self = [super init]) {
    _message = message;
    _currentIndex = 0;
  }
  return self;
}

#pragma mark - lazy
- (BOOL)hasNext{
  return _currentIndex != _message.length;
}

- (NSString *)currentCharacter{
    NSRange range = NSMakeRange(_currentIndex, 1);
    return [self.message substringWithRange:range];
}

- (void) advanceIndexBy:(NSInteger)n {
  _currentIndex += n;
}


- (NSString *) read:(NSInteger)readLength {
  NSString *readString = [_message substringWithRange:NSMakeRange(_currentIndex, readLength)];
  [self advanceIndexBy:readLength];
  return readString;
}

- (NSString *)readUntilStringOccurence:(NSString *)string {
  NSString *subString = [_message substringFromIndex:_currentIndex];
  NSRange foundRange = [subString rangeOfString:string];
  if (foundRange.location != NSNotFound) {
    [self advanceIndexBy: foundRange.location-0+1];
    return [_message substringToIndex:foundRange.location];
  } else {
    _currentIndex = string.length;
    return subString;
  }
}

- (NSString *)readUntilEnd {
  return [_message substringFromIndex:_currentIndex];
}

@end
